package com.juzhi.dvrapp.activity;

import android.location.Address;
import android.location.Geocoder;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.juzhi.dvrapp.CamApp;
import com.juzhi.dvrapp.R;
import com.juzhi.dvrapp.bean.Device;
import com.juzhi.dvrapp.manager.DeviceManager;
import com.juzhi.dvrapp.utils.Config;
import com.juzhi.dvrapp.utils.MLog;
import com.juzhi.dvrapp.utils.T;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;

public class DeviceFenceActivity extends BaseAcitivity implements OnMapReadyCallback,
        SeekBar.OnSeekBarChangeListener,
        GoogleMap.OnMapClickListener,
        GoogleMap.OnMarkerDragListener {

    @BindView(R.id.setting_map_seekbar)
    SeekBar mapSeekbar;
    @BindView(R.id.setting_map_circle_num)
    TextView mCircleNum;
    private GoogleMap mMap;
    private Marker marker;  //标注
    private Circle circle;  //圆
    private int seekBarNum = 10;
    private final int MAP_ACCURACY = 100;
    private String ssid;
    private DeviceManager deviceManager;
    private Device device;


    @Override
    public int getLayoutId() {
        return R.layout.activity_setting_map;
    }

    @Override
    protected void initView() {
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        ssid = getIntent().getStringExtra(Config.SSID);
        deviceManager = DeviceManager.getDeviceManager(CamApp.getContext());
        device = deviceManager.getDevice(ssid);
        initHeaderView();
        setTitleText(getResources().getString(R.string.setting_map));

        mapSeekbar.setMax(100);
        mapSeekbar.setProgress(seekBarNum);
        mCircleNum.setText(seekBarNum * MAP_ACCURACY + "米");


    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setOnMapClickListener(this);
        mMap.setOnMarkerDragListener(this);
        mapSeekbar.setOnSeekBarChangeListener(this);


        if (device.getLatLng()!=null){

            setFenceView(device.getLatLng());
            mCircleNum.setText(device.getFenceRadius() + "米");
            mapSeekbar.setProgress(device.getFenceRadius() / MAP_ACCURACY);

            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(device.getLatLng(), 13));
        }else {
            // Add a marker in Sydney and move the camera
            LatLng sydney = new LatLng(22.582200, 113.925992);
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
        }
    }

    @Override
    protected void function() {
        super.function();
        device.setLatLng(marker.getPosition());
        device.setFenceRadius(seekBarNum * MAP_ACCURACY);
        T.showShort(getResources().getString(R.string.string_setting_succeed));
        finish();
    }

    /**
     *
     */
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        seekBarNum = progress;
        if (circle != null)
            circle.remove();
        circle = mMap.addCircle(new CircleOptions()
                .center(marker.getPosition())
                .radius(seekBarNum * MAP_ACCURACY)
                .strokeWidth(5)  //圆圈线的宽
                .strokeColor(getResources().getColor(R.color.colorAccent))   //圆圈线的颜色
                .fillColor(getResources().getColor(R.color.map_circle_fill))     //圆圈内填充的颜色

        );

        mCircleNum.setText(seekBarNum * MAP_ACCURACY + "米");
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    /**
     * 地图点击事件
     *
     * @param latLng
     */
    @Override
    public void onMapClick(LatLng latLng) {


        setFenceView(latLng);
    }

    /**
     * 标注移动事件 开始
     *
     * @param marker
     */
    @Override
    public void onMarkerDragStart(Marker marker) {

    }

    /**
     * 标注移动事件 移动中 坐标一直回调
     *
     * @param marker
     */
    @Override
    public void onMarkerDrag(Marker marker) {

    }

    /**
     * 标注移动事件 移动完成
     *
     * @param marker
     */
    @Override
    public void onMarkerDragEnd(Marker marker) {
        if (circle != null)
            circle.remove();
        circle = mMap.addCircle(new CircleOptions()
                .center(marker.getPosition())
                .radius(seekBarNum * MAP_ACCURACY)
                .strokeWidth(5)  //圆圈线的宽
                .strokeColor(getResources().getColor(R.color.colorAccent))   //圆圈线的颜色
                .fillColor(getResources().getColor(R.color.map_circle_fill))//圆圈内填充的颜色
        );
    }

    public void setFenceView(LatLng fenceView) {

        List<Address> addresses;
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        String addStr = null;
        try {
            addresses = geocoder.getFromLocation(fenceView.latitude, fenceView.longitude, 1);
            String address = addresses.get(0).getAddressLine(0);
            String city = addresses.get(0).getLocality();
            String state = addresses.get(0).getAdminArea();
            String zipCode = addresses.get(0).getPostalCode();
            String country = addresses.get(0).getCountryCode();

            addStr = address + "," + city + "," + state + "," + zipCode + "," + country;
            MLog.e("选择地址", addStr);
        } catch (IOException e) {
            e.printStackTrace();
        }


        if (mapSeekbar.getVisibility() == View.GONE)
            mapSeekbar.setVisibility(View.VISIBLE);
        if (mCircleNum.getVisibility() == View.GONE)
            mCircleNum.setVisibility(View.VISIBLE);

        if (marker != null)
            marker.remove();
        marker = mMap.addMarker(new MarkerOptions().position(fenceView).title("栅栏中心点").draggable(true));


        if (circle != null)
            circle.remove();
        circle = mMap.addCircle(new CircleOptions()
                .center(marker.getPosition())
                .radius(seekBarNum * MAP_ACCURACY)
                .strokeWidth(5)  //圆圈线的宽
                .strokeColor(getResources().getColor(R.color.colorAccent))   //圆圈线的颜色
                .fillColor(getResources().getColor(R.color.map_circle_fill))//圆圈内填充的颜色
        );
    }
}
